package mroute

import (
	"github.com/gin-gonic/gin"
	"mygo/mystruct"
	"mygo/mymongo"
	"mygo/myws"
	"mygo/global"
	"mygo/mroute/utils"
	"strings"
)

/* =================================================================================
   非认证接口
*/

// 获取用户信息
func Apicache(c *gin.Context) {
	UserNameBoot := c.GetHeader("UserNameBoot")
	Muserboot := mymongo.Get_Chcae_User(UserNameBoot, global.Mtoken.Key)
	c.JSON(mystruct.StatusOK, gin.H{"msg": Muserboot})
}
// 后端缓存信息接口
func MyChcaeModel(cont *gin.Context) {
	switch cont.Request.Method {
		case "GET":
			switch cont.Query("model") {
				case "user":
					cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": mymongo.See_Chcae_User()})
				case "ws":
					cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": myws.See_clients()})
				default:
					cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "参数错误"})
			}
		case "POST":
			value := cont.PostForm("value")
			switch cont.PostForm("model") {
				case "user":
					mymongo.Del_Chcae_User(value)
					cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "操作完成"})
				case "ws":
					myws.Del_clients(value)
					cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": "操作完成"})
				default:
					cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "参数错误"})
			}
	}
}
// 获取请求源IP接口
func MyresIp(cont *gin.Context) {
	clientIP := utils.GetClientIP(cont)
	cont.String(mystruct.StatusOK, clientIP)
}

/* =================================================================================
   索引接口
*/
func MyApiIndexes(cont *gin.Context) {
	model := cont.DefaultPostForm("model", "")
	apiid := cont.DefaultPostForm("code", "")
	value := cont.DefaultPostForm("value", "")
	codb  := mymongo.Get_Code(apiid)
	if codb == nil {
   	cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "标识不存在"})
   	return	
   }

	switch model {
		case "see":
			ret := mymongo.ListAllIndexes(codb.Cur)
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": ret})

		case "add":
			parts := strings.Split(value, ",")
			bol, err := mymongo.CreateSingleIndex(codb.Cur, parts)
			if err != nil {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
			}else{
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": bol})
			}

		case "del":
			bol, err := mymongo.DropSingleIndex(codb.Cur, value)
			if err != nil {
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": err.Error()})
			}else{
				cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeOk, "msg": bol})
			}

		default:
			cont.JSON(mystruct.StatusOK, gin.H{"code": mystruct.MyCodeErr, "msg": "参数错误"})
	}
}